package com.jh.fcsm.service.inf.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jh.fcsm.beans.inf.InfApp;
import com.jh.fcsm.beans.inf.vo.InfAppVo;
import com.jh.fcsm.common.BaseServiceImpl;
import com.jh.fcsm.common.exception.ServiceException;
import com.jh.fcsm.constant.CommonConstant;
import com.jh.fcsm.dao.inf.InfAppMapper;
import com.jh.fcsm.service.inf.InfAppService;
import com.jh.fcsm.util.security.UUIDUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import java.util.List;
import java.util.Map;

//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;

/**
 * @Description: 应用令牌秘钥配置Service业务层处理
 *
 * @author linqiang
 * @date 2022-03-01 12:54:48
 */
@Service
@CacheConfig(cacheNames = CommonConstant.SYS_REDIS+"InfAppServiceImpl")
public class InfAppServiceImpl extends BaseServiceImpl<InfAppMapper, InfApp> implements InfAppService {

//	private static final Logger logger = LoggerFactory.getLogger(InfAppServiceImpl.class);
    @Autowired
    private InfAppMapper infAppMapper;

	@Override
	@Transactional(readOnly = false)
	/**
	 *@Description: 保存或更新应用令牌秘钥配置
	 *@param infApp 应用令牌秘钥配置对象
	 *@return String 应用令牌秘钥配置ID
	 *@Author: linqiang
	 */
	@CacheEvict(value = CommonConstant.SYS_REDIS+"InfAppServiceImpl", allEntries = true)
	public String saveOrUpdate(InfApp infApp) {
		if(infApp==null){
			throw new ServiceException("数据异常");
		}
		if(StringUtils.isEmpty(infApp.getId())){
			//新增
			infApp.setId(UUIDUtils.getUUID());
			checkoutAppKey(infApp.getAppKey());
			infAppMapper.insertSelective(infApp);
		}else{
			//避免页面传入修改
			infApp.setYn(null);
			InfApp app=infAppMapper.selectByPrimaryKey(infApp.getId());
			if(CommonConstant.FLAG_NO.equals(infApp.getStatus())) {
				//删除关联数据
				infAppMapper.deleteAppKey(app.getAppKey());
			}
			if(!StringUtils.isEmpty(infApp.getAppKey())&&!app.getAppKey().equals(infApp.getAppKey())) {
				checkoutAppKey(infApp.getAppKey());
				infAppMapper.updateAppKey(infApp.getAppKey(), app.getAppKey());
			}
			infAppMapper.updateByPrimaryKeySelective(infApp);
		}
		return infApp.getId();
	}

	/**
	 * 判断appKey是否重复
	 * @param appKey
	 */
	private void checkoutAppKey(String appKey) {
		Example example=new Example(InfApp.class);
		Criteria criteria=example.createCriteria();
		criteria.andEqualTo("yn",CommonConstant.FLAG_YES);
		//查询条件
		criteria.andEqualTo("appKey",appKey);
		int row=infAppMapper.selectCountByExample(example);
		if(row>0) {
			throw new ServiceException("AppKey重复");
		}
	}




	@Override
	@Transactional(readOnly = false)
	/**
	 *@Description: 删除应用令牌秘钥配置
	 *@param id void 应用令牌秘钥配置ID
	 *@Author: linqiang
	 */
	@CacheEvict(value = CommonConstant.SYS_REDIS+"InfAppServiceImpl", allEntries = true)
	public void delete(List<String> ids) {
		for(String id:ids){
			InfApp teminfApp=new InfApp();
			teminfApp.setId(id);
			//TODO 做判断后方能执行删除
			InfApp app=infAppMapper.selectByPrimaryKey(id);
			if (app==null) {
				throw new ServiceException("非法请求");
			}
			//删除关联数据
			infAppMapper.deleteAppKey(app.getAppKey());
			//逻辑删除
			teminfApp.setYn(CommonConstant.FLAG_NO);
			infAppMapper.updateByPrimaryKeySelective(teminfApp);
		}
	}

	/**
	 *@Description: 查询应用令牌秘钥配置详情
	 *@param id
	 *@return InfApp
	 *@Author: linqiang
	 */
    @Override
	public InfApp findById(String id) {
		return infAppMapper.selectByPrimaryKey(id);
	}


	/**
	 *@Description: 分页查询应用令牌秘钥配置
	 *@param infAppVo
	 *@return PageInfo<InfApp>
	 *@Author: linqiang
	 */
	@Override
	public PageInfo<InfApp> findPageByQuery(InfAppVo infAppVo) {
		PageHelper.startPage(infAppVo.getPageNum(),infAppVo.getPageSize());
		Example example=new Example(InfApp.class);
		Criteria criteria=example.createCriteria();
		criteria.andEqualTo("yn",CommonConstant.FLAG_YES);
		//查询条件
		if(!StringUtils.isEmpty(infAppVo.getAppKey())){
			criteria.andLike("appKey","%"+infAppVo.getAppKey()+"%");
		}
		if(!StringUtils.isEmpty(infAppVo.getAppName())){
			criteria.andLike("appName","%"+infAppVo.getAppName()+"%");
		}
		example.orderBy("createTime").desc();
		List<InfApp> infAppList=infAppMapper.selectByExample(example);
		return new PageInfo<InfApp>(infAppList);
	}

	@Override
	/**
	 * 根据appkey 和方法名得到私钥并判断是否有方法权限
	 */
	@Cacheable(key = "#root.methodName+':'+#appKey")
	public InfApp findPrivateKey(String appKey) {
		Example example=new Example(InfApp.class);
		example.selectProperties("id","appSecret","appName","appKey");
		Criteria criteria=example.createCriteria();
		criteria.andEqualTo("appKey", appKey);
		criteria.andEqualTo("status", CommonConstant.FLAG_YES);
		criteria.andEqualTo("yn",CommonConstant.FLAG_YES);
		List<InfApp> infAppList=infAppMapper.selectByExample(example);
		if(CollectionUtils.isEmpty(infAppList)) {
			throw new ServiceException("appKey 未启用");
		}
		InfApp app=infAppList.get(0);
		return app;
	}

	@Override
	public void insertAppKeyMethodList(List<Map<String, String>> appMethodList) {
		if(CollectionUtils.isEmpty(appMethodList)) {
			throw new ServiceException("请选择权限");
		}
		infAppMapper.deleteAppKey(appMethodList.get(0).get("appKey"));
		infAppMapper.insertAppKeyMethodList(appMethodList);
	}

	@Override
	public List<String> findMethodByAppKey(String appKey) {
		return infAppMapper.findMethodByAppKey(appKey);
	}

	@Override
	public void checkMethod(String appKey, String method) {
		int row=infAppMapper.selectCountByAppKeyMethod(appKey,method);
		if(row==0) {
			throw new ServiceException("appKey:"+appKey+" 没有"+method+"权限");
		}
	}
}
